package com.itheima.tlias.controller;

import com.itheima.tlias.pojo.PageResult;
import com.itheima.tlias.pojo.Result;
import com.itheima.tlias.pojo.Student;
import com.itheima.tlias.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/students")
public class StudentController {
	@Autowired
	private StudentService studentService;

	@GetMapping("/{id}")
	public Result getById(@PathVariable("id") Integer id) {
		Student student = studentService.getById(id);
		return Result.success(student);
	}

	@GetMapping
	public Result page(
			Integer clazzId,
			Integer degree,
			String name,
			@RequestParam(defaultValue = "1") Integer page,
			@RequestParam(defaultValue = "10") Integer pageSize
	) {
		PageResult<Student> list = studentService.page(clazzId, degree, name, page, pageSize);
		return Result.success(list);
	}

	@PostMapping
	public Result save(@RequestBody Student student) {
		studentService.save(student);
		return Result.success();
	}

	//@DeleteMapping("/{id}")
	//public Result deleteById(@PathVariable("id") Integer id) {
	//	studentService.deleteById(id);
	//	return Result.success();
	//}

	@DeleteMapping("/{ids}")
	public Result deleteByIds(@PathVariable String ids) {
		String[] split = ids.split(",");
		List<Integer> idList = Arrays.stream(split)
				.map(String::trim)
				.filter(s -> !s.isEmpty())
				.map(Integer::parseInt)
				.toList();
		if (idList.isEmpty()) {
			throw new IllegalArgumentException("ID列表不能为空");
		}
		studentService.deleteByIds(idList);
		return Result.success();
	}

	@PutMapping("/violation/{id}/{score}")
	public Result updateScore(@PathVariable("id") Integer id, @PathVariable("score") Integer score) {
		studentService.updateScore(id, score);
		return Result.success();
	}

	@PutMapping
	public Result update(@RequestBody Student student) {
		studentService.update(student);
		return Result.success();
	}
}
